package com.quasar.hpatient.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.quasar.hpatient.R;


public class WidgetNumber extends LinearLayout implements View.OnClickListener {

    public interface OnSave {
        public void save(WidgetNumber item);
    }

    public OnSave onSave;


    public WidgetNumber(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr);
    }

    public WidgetNumber(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    private float number;
    private TextView minus, plus;
    private EditText value;

    public void init(Context context, AttributeSet attrs, int defStyleAttr) {
        LayoutInflater.from(context).inflate(R.layout.widget_number, this);
        value = (EditText) findViewById(R.id.value);
        minus = (TextView) findViewById(R.id.minus);
        plus = (TextView) findViewById(R.id.plus);
        final TypedArray a = getContext().obtainStyledAttributes(
                attrs, R.styleable.WidgetNumber);
        number = a.getInt(R.styleable.WidgetNumber_number_value, 1);
        a.recycle();
        //setClickable(true);
        //this.setOnClickListener(this);
        minus.setOnClickListener(this);
        plus.setOnClickListener(this);
    }

    @Override
    public void setOnClickListener(OnClickListener l) {
        //super.setOnClickListener(l);
        minus.setOnClickListener(l);
        plus.setOnClickListener(l);
    }

    public void setNumber(float num) {
        number = num;
        value.setText(num + "");
    }

    public float getNumber() {
        float result = 1;
        try {
            result = Float.valueOf(value.getText().toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public void onClick(View view) {
        if (value.getText() != null && value.getText().length() > 0 &&getNumber() > 0) {
            number =getNumber();
        } else {
            number = 1;
            value.setText("1");
        }
        if (view == minus) {
            if (number > 0.5) {
                number=number-0.5f;
                value.setText(number + "");
            } else {
                Toast.makeText(getContext(), "至少服用一个规格", Toast.LENGTH_LONG).show();
            }
        } else if (view == plus) {
            number=number+0.5f;
            value.setText(number + "");
        }
        if (onSave != null) {
            onSave.save(this);
        }
    }
}